package com.xqb.modules.controller.media;

import com.xqb.common.annotation.Log;
import com.xqb.common.constants.MyConstants;
import com.xqb.common.core.controller.BaseController;
import com.xqb.common.core.domain.AjaxResult;
import com.xqb.common.core.page.TableDataInfo;
import com.xqb.common.enums.BusinessType;
import com.xqb.common.utils.SecurityUtils;
import com.xqb.common.utils.SnowflakeIdWorker;
import com.xqb.common.utils.poi.ExcelUtil;
import com.xqb.common.utils.vod.Signature;
import com.xqb.modules.domain.po.MedMedia;
import com.xqb.modules.service.IMedMediaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

/**
 * 媒资Controller
 * 
 * @author xqb
 * @date 2024-10-15
 */
@RestController
@RequestMapping("/media/media")
public class MedMediaController extends BaseController
{
    @Autowired
    private IMedMediaService medMediaService;
    private SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 1);

    /**
     * 获取上传视频的授权签名
     */
    @PreAuthorize("@ss.hasPermi('media:media:upload')")
    @PostMapping("/getSign")
    public AjaxResult getSign() {
        Signature sign = new Signature();
        // 设置 App 的云 API 密钥
        sign.setSecretId(MyConstants.VOD_ACCESS_KEY_ID);
        sign.setSecretKey(MyConstants.VOD_ACCESS_KEY_SECRET);
        sign.setCurrentTime(System.currentTimeMillis() / 1000);
        sign.setRandom(new Random().nextInt(java.lang.Integer.MAX_VALUE));
        sign.setSignValidDuration(MyConstants.VOD_SIGN_EXPIRE); // 签名有效期：2天
        try {
            String signature = sign.getUploadSignature();
            return success("signature : " + signature);
        } catch (Exception e) {
            logger.error("获取签名失败", e);
            return error("获取签名失败");
        }
    }

    /**
     * 上传视频
     */
    @PreAuthorize("@ss.hasPermi('media:media:upload')")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }

        //获取当前用户信息
        String username = SecurityUtils.getUsername();
        // 获取文件字节数组
        byte[] bytes = file.getBytes();
        // 获取文件名
        String fileName = file.getOriginalFilename();
//        // 查询文件名是否存在
//        boolean isExits = medFileService.isExists("file_name", fileName);
//        if (isExits) {
//            return AjaxResult.error("文件已存在", fileName);
//        }

        // 获取文件后缀
        String fileSuffix = null;
        if (fileName != null) {
            fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        }
        // 判断文件类型是否支持
        if (!".jpg".equalsIgnoreCase(fileSuffix) && !".png".equalsIgnoreCase(fileSuffix) && !".gif".equalsIgnoreCase(fileSuffix) && !".docx".equalsIgnoreCase(fileSuffix) && !".doc".equalsIgnoreCase(fileSuffix) && !".pptx".equalsIgnoreCase(fileSuffix)) {
            return AjaxResult.error("文件类型不支持");
        }
        // 获取文件大小
        long fileSize = file.getSize();
//        // 获取文件的MD5值
//        String md5Hex = DigestUtils.md5Hex(bytes);
        // 创建临时文件
        File tempFile = File.createTempFile(fileName, fileSuffix);
        // 将MultipartFile转换为File
        file.transferTo(tempFile);
        // 获取临时文件路径
        String filePath = tempFile.getAbsolutePath();
        // 获取媒体类型
        String contentType = file.getContentType();
        // 雪花算法生成minio中的对象名
        String snowflakeId = String.valueOf(idWorker.nextId());
        return success(medMediaService.uploadMedia(filePath));
    }


    /**
     * 查询媒资列表
     */
    @PreAuthorize("@ss.hasPermi('media:media:list')")
    @GetMapping("/list")
    public TableDataInfo list(MedMedia medMedia)
    {
        startPage();
        List<MedMedia> list = medMediaService.selectMedMediaList(medMedia);
        return getDataTable(list);
    }

    /**
     * 导出媒资列表
     */
    @PreAuthorize("@ss.hasPermi('media:media:export')")
    @Log(title = "媒资", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MedMedia medMedia)
    {
        List<MedMedia> list = medMediaService.selectMedMediaList(medMedia);
        ExcelUtil<MedMedia> util = new ExcelUtil<MedMedia>(MedMedia.class);
        util.exportExcel(response, list, "媒资数据");
    }

    /**
     * 获取媒资详细信息
     */
    @PreAuthorize("@ss.hasPermi('media:media:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(medMediaService.selectMedMediaById(id));
    }

    /**
     * 新增媒资
     */
    @PreAuthorize("@ss.hasPermi('media:media:add')")
    @Log(title = "媒资", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MedMedia medMedia)
    {
        return toAjax(medMediaService.insertMedMedia(medMedia));
    }

    /**
     * 修改媒资
     */
    @PreAuthorize("@ss.hasPermi('media:media:edit')")
    @Log(title = "媒资", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MedMedia medMedia)
    {
        return toAjax(medMediaService.updateMedMedia(medMedia));
    }

    /**
     * 删除媒资
     */
    @PreAuthorize("@ss.hasPermi('media:media:remove')")
    @Log(title = "媒资", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(medMediaService.deleteMedMediaByIds(ids));
    }

//    /**
//     * 上传视频接口
//     */
//    @PostMapping("/upload")
}
